package com.dup.jxlh.admin.config;

import com.dup.jxlh.admin.service.auth.AuthRedisTokenStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Value("${spring.security.oauth2.clientId}")
    private String clientId;
    @Value("${spring.security.oauth2.clientSecret}")
    private String clientSecret;
    @Value("${spring.security.oauth2.grantType}")
    private String grantType;
    @Value("${spring.security.oauth2.scope}")
    private String scope;
    @Value("${spring.security.oauth2.validTime}")
    private Integer validTime;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AuthRedisTokenStoreService authRedisTokenStoreService;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(clientId)
                .secret(new BCryptPasswordEncoder().encode(clientSecret))
                .scopes(scope)
                .authorizedGrantTypes(grantType)
                .accessTokenValiditySeconds(validTime)
                .and()
                .withClient(clientId)
                .secret(new BCryptPasswordEncoder().encode(clientSecret))
                .scopes(scope)
                .authorizedGrantTypes("client_credentials")
                .accessTokenValiditySeconds(validTime);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(authRedisTokenStoreService)
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
}
